package modalities;

import java.util.Observer;

public class VoiceLevelManager extends Thread{

	Double powerDefinedByFunction = 0.0;
	Double voicePowerMeasured = 0.0;
	Double tmp;
	ObservableThing ob;
	
	Double decreaseValue = 0.3;
	Observer chief;
	Boolean endOfListeningRequested = false;
	
	
	public VoiceLevelManager( Observer decider){
		this.chief = decider;
		this.ob = new ObservableThing();
		ob.addObserver(this.chief);
	}

	public void run() {
		//infinite loop that decrease the power level. To increase id
		//events must increase the variable.
		while(!endOfListeningRequested)
		{
			
			try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
			
			//Lock the variable.
			synchronized (voicePowerMeasured) {
				
				//If no change since last loop
				if(voicePowerMeasured == 0)
				{
					powerDefinedByFunction  -= decreaseValue;
					if (powerDefinedByFunction <= 0.0)
					{
						powerDefinedByFunction = 0.0;
					}
				}
				//Add the voice if not null. 0.5 .. 1
				
				powerDefinedByFunction += voicePowerMeasured*0.2;
				if(powerDefinedByFunction >= 1)
				{
					powerDefinedByFunction =1.0;
				}
				voicePowerMeasured = 0.0; //Reset for the next loop. If voice running, will be ret in the set function.
				ob.externalSetChanged();
				ob.notifyObservers(new Message(powerDefinedByFunction, true));
			}
			
			try {Thread.sleep(375);} catch (InterruptedException e) {e.printStackTrace();}
			
		}
		System.out.println("LevelManager Stopped");
	}
	
	public void setEndOfListeningRequested(Boolean endOfListeningRequested) {
		this.endOfListeningRequested = endOfListeningRequested;
	}

	public void setCurrentValue(Double voicePowerMeasured){
		
		synchronized (voicePowerMeasured) {
			this.voicePowerMeasured =  voicePowerMeasured;
		}
		
	}
	
}
